package _99练习;


<<<<<<< HEAD
/**
 * @author ZhiCheng Qian
 * @since 2021/11/30 19:29
 */
=======

>>>>>>> 1c69d32fc055e0010098b09f71795769d9a12acd
public class Racing {

    // 8.
    // 龟兔赛跑
    // 100米
    // 乌龟每次跑3~5米	 随机停顿200~300ms
    // 兔子每次跑2~10米 随机停顿100~500ms
    // 兔子跑完100米结束
    // 主线程
    // 显示比赛开始
    // 创建乌龟的线程、兔子线程。并启动线程
    // 主线程 等乌龟和兔子线程运行完后，显示比赛结果

    public static void main(String[] args) throws InterruptedException {

        Thread turtleThread = new Thread(new RacingDemo(), "乌龟");
        Thread rabbitThread = new Thread(new RacingDemo(), "兔子");

        turtleThread.setDaemon(true);
        rabbitThread.setDaemon(true);

        turtleThread.start();
        rabbitThread.start();
        
        while (true) {
            if (!turtleThread.isAlive()) {
                break;
            } else if (!rabbitThread.isAlive()) {
                break;
            }
        }


    }
}


class RacingDemo extends Thread {
    int distance = 0;


    @Override
    public void run() {
        loop:
        while (true) {

            if (Thread.currentThread().getName().equals("乌龟")) {
                int currentDistance = (int) (Math.random() * (5 - 3 + 1) + 3);
                System.out.println("乌龟跑了" + currentDistance);
                distance += currentDistance;
                if (distance > 100) {
                    System.out.println(Thread.currentThread().getName() + "赢了");
                    break loop;
                }
                int sleepTime = (int) (Math.random() * (300 - 200 + 1) + 200);
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else if (Thread.currentThread().getName().equals("兔子")) {
                int currentDistance = (int) (Math.random() * (10 - 2 + 1) + 2);
                System.out.println("兔子跑了" + currentDistance);
                distance += currentDistance;
                if (distance > 100) {
                    System.out.println(Thread.currentThread().getName() + "赢了");
                    break loop;
                }
                int sleepTime = (int) (Math.random() * (500 - 100 + 1) + 100);
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
